import wxApi from "./utils/wxApi";
import config from "./config";
import utils from "./utils/util";
import request from "./utils/request";

export default {
  data: {
    loginStorageKey: `pythonToken_${config.env}`,
    storeStorageKey: `storeJsData_${config.env}`,
    currentUserAgentInfo: {},
    globalEnabled: true,
    customSize: {},
    loginTempData: {},
    hasLogin: false,
    loginInfo: {
      token: ""
    },
    needLogin: false,
    mineInfo: {},
    demoData:{
      num:0
    }
  },
  globalData: ["loginInfo", "hasLogin", "needLogin", "teamStatus"],
  autoSaveToStorage() {
    return wxApi("setStorage", { key: this.data.storeStorageKey, data: this.data });
  },
  initStorageData() {
    let startTime = +new Date();
    try {
      const value = wx.getStorageSync(this.data.storeStorageKey);
      console.log("value", value);
      if (value && utils.isObj(value)) {
        this.data = utils.deepObjectMerge(this.data, value);
        console.info("deepObjectMerge", +new Date() - startTime + "ms");
      }
    } catch (e) {
      console.error("deepObjectMerge error", e);
    }
  },
  getAgentInfo(newGet = false) {
    let startTime = +new Date();
    return new Promise((resolve, reject) => {
      // 获取 设备信息 网络情况 电池信息
      if (!newGet && Object.keys(this.data.currentUserAgentInfo).length) {
        resolve({ success: true, data: this.data.currentUserAgentInfo });
      }
      Promise.all([wxApi("getSystemInfo")
        // wxApi("getNetworkType"),
        // wxApi("getBatteryInfo")
      ]).then(res => {
        let tempData = {};
        res.forEach(res => {
          res.errMsg && delete res.errMsg;
          tempData = Object.assign(tempData, res);
        });
        this.data.currentUserAgentInfo = tempData;
        console.log("getAgentInfo:", +new Date() - startTime + "ms");
        resolve({ success: true, data: tempData });
      }).catch(error => {
        resolve({ success: false, data: error });
      });
    });
  },
  setJavaToken(data) {
    this.data.loginInfo = data;
    return new Promise((resolve) => {
      this.isLogin();
      resolve();
    });
  },
  removeJavaToken() {
    return new Promise((resolve) => {
      this.data.loginInfo = {};
      this.isLogin();
      resolve();
    });
  },
  getStorageJavaToken() {
    const loginInfo = this.data.loginInfo;
    Object.keys(loginInfo).length && request.setToken(loginInfo.token);
    this.isLogin();
    return loginInfo;
  },

  isLogin() {
    const data = this.data.loginInfo || {};
    this.data.hasLogin = !!(data && utils.isObj(data) && data.token);
    return this.data.hasLogin;
  }
  // 微信登录的逻辑
  //默认 false，为 true 会无脑更新所有实例
  //updateAll: true
};
